package com.pjc.dao;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteResult;
import com.pjc.db.MongoDB;
import com.pjc.db.MongoUtils;
import com.pjc.model.chat.SysMsg;
import com.pjc.utils.Utils;

/**
 * 系统消息数据访问层
 * 
 * @author 王畅
 * @since 2015年6月21日
 */
public class SysMsgDao {

	protected static final Logger LOG = LoggerFactory.getLogger(SysMsgDao.class);

	/**
	 * 获取表信息
	 * 
	 * @return
	 * @throws Exception
	 */
	private static DBCollection getSysMsgCollection() throws Exception {
		return MongoDB.getDB("jkt").getCollection("SysMsg");
	}

	/**
	 * 保存系统消息
	 * 
	 * @author 王畅
	 * @param msg
	 * @return
	 * @throws Exception
	 */
	public static boolean saveSysMsg(SysMsg msg) throws Exception {
		DBObject val = new BasicDBObject();
		val.put("msgId", Integer.valueOf(msg.getMsgId()));
		val.put("appId", msg.getAppId());
		val.put("fromUser", msg.getFromUser());
		val.put("toUserId", msg.getToUserId());
		val.put("other", msg.getOther());
		val.put("type", Integer.valueOf(msg.getType()));
		val.put("data", msg.getData());
		val.put("time", Long.valueOf(msg.getTime()));
		WriteResult writeResult = MongoUtils.save(getSysMsgCollection(), val);
		return writeResult.getError() == null;
	}

	/**
	 * 获取离线系统消息
	 * 
	 * @param appID
	 * @param userID
	 * @param logoutTime
	 * @return
	 * @throws Exception
	 */
	public static List<SysMsg> getOfflineMsg(String appID, String userID, long logoutTime) throws Exception {
		DBObject query = new BasicDBObject();
		query.put("toUserId", userID);
		query.put("appId", appID);
		query.put("time", new BasicDBObject("$gt", Long.valueOf(logoutTime)));
		DBObject fields = new BasicDBObject();
		fields.put("_id", Integer.valueOf(0));
		DBCursor cursor = MongoUtils.findAll(getSysMsgCollection(), query, null);

		if (cursor == null) {
			return null;
		}
		List<SysMsg> sysMsgs = new ArrayList<SysMsg>();
		try {
			while (cursor.hasNext()) {
				DBObject dbObject = cursor.next();
				sysMsgs.add((SysMsg) Utils.JSON2Object(dbObject.toString(), SysMsg.class));
			}
		} finally {
			cursor.close();
		}
		return sysMsgs;
	}

}
